package org.s63;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.s63.entity.User;
import org.s63.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String getPage(User user,
                          @RequestParam(required = false, defaultValue = "1") int pageNum,
                          @RequestParam(required = false, defaultValue = "5") int pageSize,
                          Model model) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userService.getAll(user);
        PageInfo<User> pageInfo = PageInfo.of(list);
        model.addAttribute("page", pageInfo);
        model.addAttribute("user", user);
        return "user/index";
    }

    @GetMapping("/del")
    public String del(Integer id) {
        userService.del(id);
        return "redirect:/users";
    }

    @GetMapping("/toAdd")
    public String add() {
        return "user/add";
    }

    @PostMapping("/add")
    public String add(User user) {
        userService.add(user);
        return "redirect:/users";
    }
}
